package utils

import (
	"bytes"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
)

type H map[string]interface{}

type Ding struct {
	data        H
	HookUrl     string
	AtMobileTxt string
	AtAllTxt    string
}

type DingResult struct {
	ErrCode int    `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
}

func NewDing(token string) *Ding {
	return &Ding{
		data:    make(H),
		HookUrl: "https://oapi.dingtalk.com/robot/send?access_token=" + token,
	}
}

func (ds *Ding) At(mobiles []string, isAtAll bool) *Ding {
	if !isAtAll {
		for _, mobile := range mobiles {
			ds.AtMobileTxt += " @" + mobile
		}
	} else {
		ds.AtAllTxt = "@所有人 "
	}

	ds.data["at"] = H{
		"atMobiles": mobiles,
		"isAtAll":   isAtAll,
	}

	return ds
}

func (ds *Ding) Markdown(title string, content string) *Ding {
	ds.data["msgtype"] = "markdown"
	ds.data["markdown"] = H{
		"title": title,
		"text":  ds.AtAllTxt + content + ds.AtMobileTxt,
	}

	return ds
}

func (ds *Ding) Text(content string) *Ding {
	ds.data["msgtype"] = "text"
	ds.data["text"] = H{
		"content": ds.AtAllTxt + content + ds.AtMobileTxt,
	}

	return ds
}

func (ds *Ding) SendTest() H {
	return ds.data
}

func (ds *Ding) Send() error {
	b, err := json.Marshal(ds.data)

	resp, err := http.Post(ds.HookUrl,
		"application/json",
		bytes.NewReader(b))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	ret := &DingResult{}
	err = json.Unmarshal(body, ret)

	if err != nil {
		return err
	}

	if ret.ErrCode != 0 {
		return errors.New(ret.ErrMsg)
	}

	return nil
}
